﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using QualitySupervision.Models;

namespace QualitySupervision.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public AuthenticationController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpPost]
        public ActionResult RequestToken(string name, string password)
        {
            if (name == null && password == null)
                return BadRequest("Invalid Request");
            var tokenParameter = _configuration.GetSection("tokenParameter").Get<TokenParameter>();
            var claims = new Claim[]
            {
                 new Claim(ClaimTypes.Name,name),
                 new Claim(ClaimTypes.Role,"Root"),
            };
            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(tokenParameter.Secret));
            var token = new JwtSecurityToken(
                        issuer: tokenParameter.Issuer,
                        audience: tokenParameter.Audience,
                        claims: claims,
                        notBefore: DateTime.Now,
                        expires: DateTime.Now.AddMinutes(tokenParameter.AccessExpiration),
                        signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            //生成Token
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return Ok(jwtToken);
        }
    }
}
